package com.chuangyang.fixboxmaster.ui;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.chuangyang.fixboxlib.widgets.VerificationCodeButton;
import com.chuangyang.fixboxmaster.BuildConfig;
import com.chuangyang.fixboxmaster.R;
import com.chuangyang.fixboxmaster.bean.BaseInfo;
import com.chuangyang.fixboxmaster.bean.LoginInfo;
import com.chuangyang.fixboxmaster.bean.VerifyCodeEvent;
import com.chuangyang.fixboxmaster.service.FixBoxApi;
import com.chuangyang.fixboxmaster.service.GsonRequest;
import com.chuangyang.fixboxmaster.utils.PrefUtils;

import java.util.HashMap;

import de.greenrobot.event.EventBus;

public class LoginActivity extends BaseActivity implements View.OnClickListener, TextView.OnEditorActionListener {
    private EditText mPhoneNumber;
    private EditText mVerificationCode;
    private VerificationCodeButton mBtnVerificationCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        mPhoneNumber = (EditText) findViewById(R.id.edit_phone_number);
        mPhoneNumber.setOnEditorActionListener(this);

        mVerificationCode = (EditText) findViewById(R.id.edit_verification_code);
        mVerificationCode.setOnEditorActionListener(this);

        mBtnVerificationCode = (VerificationCodeButton) findViewById(R.id.btn_verification_code);
        mBtnVerificationCode.setOnClickListener(this);

        Button mBtnLogin = (Button) findViewById(R.id.btn_login);
        mBtnLogin.setOnClickListener(this);

        TextView mAgreementTips = (TextView) findViewById(R.id.tv_fixbox_agreement);
        mAgreementTips.setPaintFlags(mAgreementTips.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
        mAgreementTips.setOnClickListener(this);
        EventBus.getDefault().register(this);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public void onEvent(VerifyCodeEvent verifyCode){
        mVerificationCode.setText(verifyCode.code);
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_verification_code:
                if (validatePhoneNumber()) {
                    if (!mBtnVerificationCode.isLoading()) {
                        mBtnVerificationCode.start();
                        HashMap<String, String> parameter = new HashMap<>();
                        parameter.put("phoneNumber", mPhoneNumber.getText().toString().trim());
                        addRequest(new GsonRequest<>(FixBoxApi.GET_VERIFY_CODE, parameter, BaseInfo.class, getVerifyCodeListener));
                    }
                }
                break;
            case R.id.tv_fixbox_agreement:
                startActivity(new Intent(this, AgreementActivity.class));
                break;

            case R.id.btn_login:
                submit();
                break;
        }

    }


    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (v == mVerificationCode) {
            switch (actionId) {
                case EditorInfo.IME_ACTION_DONE:
                    submit();
                    return true;
            }
        }
        return false;
    }

    private boolean validatePhoneNumber() {
        final String phoneNumber = mPhoneNumber.getText().toString().trim();
        if (TextUtils.isEmpty(phoneNumber)) {
            mPhoneNumber.setError("手机号不能为空!");
            return false;
        } else if (phoneNumber.length() != 11) {
            mPhoneNumber.setError("请输入正确的手机号!");
            return false;
        }
        return true;
    }

    private boolean validateVerifyCode() {
        final String verificationCode = mVerificationCode.getText().toString().trim();
        if (TextUtils.isEmpty(verificationCode)) {
            mVerificationCode.setError("验证码不能为空");
            return false;
        }
        return true;
    }

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        MenuInflater inflater = getMenuInflater();
//        inflater.inflate(R.menu.registry_menu, menu);
//        return super.onCreateOptionsMenu(menu);
//    }


//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        switch (item.getItemId()) {
//            case R.id.menu_registry:
//                startActivity(new Intent(LoginActivity.this,RegistrationActivity.class));
//                return true;
//            default:
//                return super.onOptionsItemSelected(item);
//        }
//    }

    private void submit() {
        if (validatePhoneNumber() && validateVerifyCode()) {
            HashMap<String, String> parameter = new HashMap<>();
            parameter.put("phoneNumber", mPhoneNumber.getText().toString());
            parameter.put("verifyCode", mVerificationCode.getText().toString());
            addRequest(new GsonRequest<>(FixBoxApi.USER_LOGIN, parameter, LoginInfo.class, responseLoginListener));
        }
    }


    private Response.Listener<BaseInfo> getVerifyCodeListener = new Response.Listener<BaseInfo>() {
        @Override
        public void onResponse(BaseInfo response) {
            Toast.makeText(getApplicationContext(), "验证码稍后会发送到您到手机，请注意查收", Toast.LENGTH_SHORT).show();
        }
    };


    private Response.Listener<LoginInfo> responseLoginListener = new Response.Listener<LoginInfo>() {
        @Override
        public void onResponse(LoginInfo response) {
            if (BuildConfig.DEBUG) {
                Toast.makeText(getApplicationContext(), response.result.toString(), Toast.LENGTH_SHORT).show();
            }
            PrefUtils.putString(LoginActivity.this, PrefUtils.ACCESS_TOKEN, response.result.accessToken);
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            intent.putExtra("workState", response.result.workState);
            startActivity(intent);
            LoginActivity.this.finish();
        }
    };
}
